package com.itzxx.huazhun.ui.record.valuation

import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import com.github.aachartmodel.aainfographics.aachartcreator.AASeriesElement
import com.itzxx.huazhun.data.model.ComplianceResult
import com.itzxx.huazhun.data.model.DevicesChildBean
import com.itzxx.huazhun.data.model.RecordChildBean
import com.itzxx.huazhun.data.model.RecordCurveAdminDataBean
import com.itzxx.huazhun.data.repository.HttpRequestCoroutine
import com.itzxx.huazhun.ui.device.list.DevicesListActivity
import com.itzxx.library_base_ktx.base.viewmodel.BaseViewModel
import com.itzxx.library_base_ktx.callback.databind.BooleanObservableField
import com.itzxx.library_base_ktx.callback.databind.IntObservableField
import com.itzxx.library_base_ktx.callback.databind.StringObservableField
import com.itzxx.library_base_ktx.callback.livedata.event.EventLiveData
import com.itzxx.library_base_ktx.ext.request
import com.itzxx.library_base_ktx.state.ListDataUiState

class RecordValuationViewModel : BaseViewModel() {
    //列表数据刷新
    val listDataUiStateLiveData = EventLiveData<ListDataUiState<RecordChildBean>>()

    //灭菌温度
    val sterilizationTemperatureObservableField = StringObservableField("134")

    //消毒温度
    val cleanTemperatureObservableField = StringObservableField("90")

    //是否显示设备信息
    val isVisibleDetailObservableField = BooleanObservableField(false)

    // 设备详情
    val devicesInfoLiveData = EventLiveData<DevicesChildBean>()

    var currentCheckSceneTypeIdObservableField = IntObservableField(0)

    val complianceResultLiveData = EventLiveData<ComplianceResult>()
    val noComplianceResultLiveData = EventLiveData<String>()

    var ids = arrayListOf<Int>()

    //请求数据最后索引
    var queryCurvelastIndex = 0;

    //曲线时间
    var queryCurveTimeArray = emptyList<String>()

    //曲线数据
    val queryCurveDataMap = mutableMapOf<Int, RecordCurveAdminDataBean>()

    //返回绘制曲线
    val curveDataCategoriesLiveData = MutableLiveData<ArrayList<String>>()

    //返回绘制内容
    val curveDataLiveData = MutableLiveData<ArrayList<AASeriesElement>>()

    val MAX_DRAW_NUM = 300

    var equipmentId:String? = null

    fun getCloundData(sceneType: Int, ids: ArrayList<Int>, equipmentId: String?) {
        loadingChange.showDialog.postValue("数据加载中...")
        this.currentCheckSceneTypeIdObservableField.set(sceneType)
        this.ids = ids
        this.equipmentId = equipmentId
        var tempTemperature = 0.0
        if (sceneType == 2) {
            tempTemperature = sterilizationTemperatureObservableField.get().toDouble()
        } else if (sceneType == 7) {
            tempTemperature = cleanTemperatureObservableField.get().toDouble()
        } else {
        }
        request({
            HttpRequestCoroutine.queryNumericalValueByScene(ids, sceneType, tempTemperature)
        }, {
            complianceResultLiveData.postValue(it.calculationResult.complianceResult)
            noComplianceResultLiveData.postValue(it.calculationResult.noComplianceResult)
            queryCurveTimeArray = it.calculationResult.times
            getCurveData()
        }, {

        })
        //获取设备信息
        requestDetail(equipmentId)
    }

    fun getCurveData() {
        if (queryCurveTimeArray.size - 1 == queryCurvelastIndex) {
            return
        }

        val startTime = queryCurveTimeArray[queryCurvelastIndex]
        var endtime = ""
        var isEnd = false
        if (queryCurvelastIndex + 1 == queryCurveTimeArray.size - 1) {
            endtime = queryCurveTimeArray[queryCurveTimeArray.size - 1]
            isEnd = true
        } else {
            endtime = queryCurveTimeArray[queryCurvelastIndex + 1]
        }
        request({
            HttpRequestCoroutine.queryAdminEquipmentDataCurve(
                ids,
                currentCheckSceneTypeIdObservableField.get(),
                startTime,
                endtime
            )
        }, {
            queryCurvelastIndex++
            it.forEachIndexed { index, recordCurveAdminDataBean ->
                var curveAdminDataBean = queryCurveDataMap[index]
                if (curveAdminDataBean != null) {
                    curveAdminDataBean.pressureValue.addAll(recordCurveAdminDataBean.pressureValue)
                    curveAdminDataBean.temperatureValue.addAll(recordCurveAdminDataBean.temperatureValue)
                } else {
                    curveAdminDataBean = recordCurveAdminDataBean
                }
                queryCurveDataMap[index] = curveAdminDataBean
            }
            if (isEnd) {
                onDraw()
            } else {
                getCurveData()
            }
        }, {
            loadingChange.dismissDialog.postValue(false)
        })
    }

    fun onDraw() {
        val queryCurveTimeList = arrayListOf<String>()
        //具体点数据
        val arrayType = arrayListOf<AASeriesElement>()

        for ((_, recordCurveAdminDataBean) in queryCurveDataMap) {
            //添加气压参数
            if (recordCurveAdminDataBean.pressureValue.isNotEmpty()) {
                val arrayQiya = arrayListOf<Array<Any>>()
                val stepNum = recordCurveAdminDataBean.pressureValue.size / MAX_DRAW_NUM

                recordCurveAdminDataBean.pressureValue.forEachIndexed { index, pressureValue ->
                    if (stepNum <= 1||index % stepNum == 0) {
                        arrayQiya.add(
                            arrayOf(
                                pressureValue.time,
                                pressureValue.pressure.toDouble()
                            )
                        )
                        queryCurveTimeList.add(pressureValue.time)
                    }
                }
                arrayType.add(
                    AASeriesElement()
                        .name(recordCurveAdminDataBean.pressureName)
                        .data(arrayQiya.toArray())
                )
            }

            //添加温度参数
            if (recordCurveAdminDataBean.temperatureValue.isNotEmpty()) {
                val arrayWendu = arrayListOf<Array<Any>>()
                val stepNum = recordCurveAdminDataBean.temperatureValue.size / MAX_DRAW_NUM
                recordCurveAdminDataBean.temperatureValue.forEachIndexed { index, temperatureValue ->
                    if (stepNum <= 1 || index % stepNum == 0) {
                        arrayWendu.add(
                            arrayOf(
                                temperatureValue.time,
                                temperatureValue.temperature.toDouble()
                            )
                        )
                    }
                    if(recordCurveAdminDataBean.pressureValue.isEmpty()){
                        queryCurveTimeList.add(temperatureValue.time)
                    }
                }
                arrayType.add(
                    AASeriesElement()
                        .name(recordCurveAdminDataBean.temperatureName)
                        .data(arrayWendu.toArray())
                )
            }
        }

        //绘制标题
        curveDataCategoriesLiveData.postValue(queryCurveTimeList)
        curveDataLiveData.postValue(arrayType)
        loadingChange.dismissDialog.postValue(false)
    }

    fun onValuation() {
        loadingChange.showDialog.postValue("评估中...")
        var tempTemperature = 0.0
        if (currentCheckSceneTypeIdObservableField.get() == 2) {
            tempTemperature = sterilizationTemperatureObservableField.get().toDouble()
        } else if (currentCheckSceneTypeIdObservableField.get() == 7) {
            tempTemperature = cleanTemperatureObservableField.get().toDouble()
        } else {
        }
        request({
            HttpRequestCoroutine.queryNumericalValueByScene(ids, currentCheckSceneTypeIdObservableField.get(), tempTemperature)
        }, {
            complianceResultLiveData.postValue(it.calculationResult.complianceResult)
            noComplianceResultLiveData.postValue(it.calculationResult.noComplianceResult)
            loadingChange.dismissDialog.postValue(false)
        }, {
            loadingChange.dismissDialog.postValue(false)
        })
    }


    fun addDevices() {
        baseContext.value?.let { DevicesListActivity.startActivity(it, ids) }
    }

    fun requestDetail(equipmentId: String?) {
        this.equipmentId = equipmentId
        if (!TextUtils.isEmpty(equipmentId)) {
            request({
                HttpRequestCoroutine.detectionEquipmentInfo(
                    equipmentId!!.toInt(),
                    ""
                )
            }, {
                isVisibleDetailObservableField.set(true)
                devicesInfoLiveData.postValue(it)
            }, {
                isVisibleDetailObservableField.set(false)
            })
        } else {
            isVisibleDetailObservableField.set(false)
        }
    }
}